use log::{info, warn};
use notify::{Config as NotifyConfig, RecommendedWatcher, RecursiveMode, Watcher, Event, EventKind};
use std::path::Path;
use std::sync::mpsc::channel;
use std::time::Duration;
use tokio::sync::mpsc as tokio_mpsc;

pub struct ConfigWatcher {
    config_path: String,
}

impl ConfigWatcher {
    pub fn new(config_path: String) -> Self {
        Self { config_path }
    }

    /// 启动配置文件监听
    pub fn start_watching(&self) -> tokio_mpsc::Receiver<()> {
        let (tx, rx) = tokio_mpsc::channel(10);
        let config_path = self.config_path.clone();

        std::thread::spawn(move || {
            let (notify_tx, notify_rx) = channel();

            let mut watcher: RecommendedWatcher = Watcher::new(
                move |res: Result<Event, notify::Error>| {
                    if let Ok(event) = res {
                        // 只关注修改事件
                        if matches!(event.kind, EventKind::Modify(_)) {
                            let _ = notify_tx.send(());
                        }
                    }
                },
                NotifyConfig::default().with_poll_interval(Duration::from_secs(2)),
            )
            .expect("Failed to create file watcher");

            if let Err(e) = watcher.watch(Path::new(&config_path), RecursiveMode::NonRecursive) {
                warn!("Failed to watch config file: {}", e);
                return;
            }

            info!("配置文件监听已启动: {}", config_path);

            loop {
                if notify_rx.recv().is_ok() {
                    info!("检测到配置文件变更: {}", config_path);
                    // 发送重载信号
                    if tx.blocking_send(()).is_err() {
                        break;
                    }
                    // 防抖:等待一段时间避免多次触发
                    std::thread::sleep(Duration::from_secs(1));
                }
            }
        });

        rx
    }
}
